/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package updater;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import updater.UpdateTestView;

/**
 *
 * @author rbs
 */
public class Updater implements Runnable{

    private URL url;
    private int size;
    private int down;
    private UpdateTestView view;

    private static final int MAX_BUFFER = 1024;

    public Updater(String file, UpdateTestView viewer) throws IOException {
        url = new URL(file);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        down = 0;
        size = con.getContentLength();
        view = viewer;
    }

    public int getSize() throws MalformedURLException, IOException
    {
    return size;
    }

    public void download() throws IOException
    {
        Thread thread = new Thread(this);
        thread.start();
    }
    public int getPercentage()
    {
        return (int) ((float) down / size * 100);
    }

    private void error(String error_msg)
    {
        view.ShowErrMsgDialog(error_msg);
    }

    public void run() {
        try {
            view.setButtonsDisabled(true);
            view.setStatusMsg("Downloaden...");
            view.setUpdateNonVisible();
            
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
             // Specify what portion of file to download.
            con.setRequestProperty("Range",
                    "bytes=" + down + "-");

            // Connect to server.
            con.connect();

            // Make sure response code is in the 200 range.
            if (con.getResponseCode() / 100 != 2)
                error("Server meldet Fehler bei Verbindungsaufbau:" + con.getResponseCode()
                        + " " + con.getResponseMessage());
                
            
            String fileName = url.getFile();
            RandomAccessFile file = new RandomAccessFile(fileName.substring(fileName.lastIndexOf('/') + 1), "rw");

            InputStream stream = con.getInputStream();

            while(size - down > 0)
            {
                byte buffer[];
                if (size - down > MAX_BUFFER)
                    buffer = new byte[MAX_BUFFER];
                else
                    buffer = new byte[size - down];

                int read = stream.read(buffer);
                if (read == -1 )
                    break;

                file.write(buffer, 0, read);
                down += read;
                view.setStatusBar((int) ((float) down / size * 100));
            }
            file.close();
            stream.close();

            view.setStatusMsg("Entpacken...");

            File zip_file = new File("fwdisp.zip");
            ZipExtractor zip = new ZipExtractor();

            try {
                File temp = new File("update123" + File.separatorChar);

                zip.extractArchive(zip_file, temp);
            } catch (Exception ex) {
                Logger.getLogger(UpdateTestView.class.getName()).log(Level.SEVERE, null, ex);
                error("Fehler bei Entpacken: Zip-Datei nicht vorhanden.");
            }

            /*
            if(zip_file.exists()){
                if ( !zip_file.delete())
                {
                    view.ShowWarnMsgDialog("Konnte Datei nicht löschen: " + zip_file.getName());
                }
            }
             * S
             */

            view.setStatusMsg("Fertig");
            view.setButtonsDisabled(false);
            if(true) //view.getAutoMode())
                view.exit(0);
            
        }
        catch (IOException ex) {
            error("Fehler bei der Verbindung aufgetreten: " + ex);
        }
    }
}
